<!-- 客户组（部门）列表选择组件 -->
<template>
    <div>
        <el-cascader separator="-" @change="change" filterable clearable :props="{
            lazy: true,
            checkStrictly: true,
            lazyLoad: loadData,
            label: 'name',
            value: 'id',
            emitPath: false,
        }" style="margin-right: 20px" v-model="selectedValue"></el-cascader>
    </div>
</template>

<script>
    export default {
        props: {
            value: {
                type: [Number, String, Array],
                default: null
            }
        },
        data() {
            return {
                selectList: [],
                selectedValue: this.value // 使用本地 data 属性来保存选中的值
            }
        },
        watch: {
            value: {
                immediate: true,
                handler(newVal) {
                    this.selectedValue = newVal; // 监听外部变化以保持同步
                }
            }
        },
        mounted() {
            
        },
        methods: {
            loadData(node, resolve) { 
                const {
                    level
                } = node;
                const pid = level === 0 ? 0 : node.value

                this.$axios.post(`/Enterprise/List`,{
                    pageIndex: 1,
                    pageSize: 9999,
                    parentId: pid
                }).then((datas) => {
                    const nodes = datas.rows
                        .map(c => ({
                            id: c.id,
                            name: pid > 0? c.department : c.name,
                            leaf: pid > 0? true : false,
                            // leaf: c.hasChildren === false // 根据实际接口返回字段判断
                        }))
                    resolve(nodes)
                }).catch(() => {
                    resolve([]) // 清空加载状态
                    this.$message.error('加载失败')
                })
            },
            change(val){
                this.$emit('change', this.selectedValue); // 触发 change 事件传递新值
                this.$emit('input', this.selectedValue); // 如果支持 v-model，则也触发 input 事件
            }
        }
    }
</script>